import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageResizer {
	public static void main(String[] args) throws IOException {
		ImageResizer resizer = new ImageResizer();
		String path = "assets/img/faces";
		resizer.restoreFromBackups(new File(path));
		resizer.resizeDirectoryAndSave(new File(path), new Dimension(80, 112),
				"png");

	}

	public BufferedImage resize(BufferedImage image, Dimension size) {
		Image resizedImage = image.getScaledInstance((int) size.getWidth(),
				(int) size.getHeight(), BufferedImage.SCALE_SMOOTH);
		BufferedImage result = new BufferedImage((int) size.getWidth(),
				(int) size.getHeight(), image.getType());
		Graphics2D g = result.createGraphics();
		g.drawImage(resizedImage, 0, 0, null);
		g.dispose();
		return result;
	}

	public void resizeDirectoryAndSave(File directory, Dimension size,
			final String extension) throws IOException {
		System.out.println(directory);
		if (!directory.isDirectory()) {
			throw new IllegalArgumentException();
		}
		for (File file : directory.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				if (name.endsWith(extension)) {
					return true;
				}
				return false;
			}
		})) {
			String fileName = file.getPath();
			BufferedImage resizedImage = resize(ImageIO.read(file), size);
			file.renameTo(new File(fileName + ".bak"));
			ImageIO.write(resizedImage, "png", new File(fileName));
		}
	}

	public void restoreFromBackups(File directory) {
		for (File file : directory.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				if (name.endsWith("bak")) {
					return true;
				}
				return false;
			}

		})) {
			String filename = file.getPath();
			filename = filename.substring(0, filename.length() - 4);
			File newFile = new File(filename);
			if (newFile.exists()) {
				newFile.delete();
			}
			file.renameTo(newFile);
		}
	}
}